package com.example.javalib.changsign;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;


/**
 * @Description:
 * @author: zcs
 * @email: 1059737741@qq.com
 * create at 2022/2/24 16:04
 */
public class SignHelper {

    private static final String key = "12345678";
    //方式1
    public static void main1(String[] args) throws Exception {
        HashMap<String,Object> map = new HashMap<>();
        map.put("sysType",12);
        map.put("nonce","111");
        map.put("countryCode",86);
        map.put("useFor",1);
        map.put("mobile","18521051910");

        String sign = sign(map);
        System.out.println(sign);
        map.put("sign",sign);
    }
    public static String sign(HashMap<String,Object> params) throws Exception {
        List<String> paramKeys = new ArrayList<>();
        paramKeys.addAll(params.keySet());
        Collections.sort(paramKeys);

        StringBuilder stringBuilder = new StringBuilder();
        for (String paramKey : paramKeys) {
            Object value =  params.get(paramKey);
            if (value == null) {
                continue;
            }
            stringBuilder.append(paramKey);
            stringBuilder.append("=");
            stringBuilder.append(value);
            stringBuilder.append("&");
        }
        stringBuilder.append("key=");
        stringBuilder.append(key);

        return HMACSHA256Helper.HMACSHA256(stringBuilder.toString(),key);
    }


    //方式2
    public static void main(String[] args) throws Exception {
        CommonParams commonParams = new CommonParams();
        commonParams.setSysType(12);
        commonParams.setNonce("111");
        commonParams.setCountryCode(86);
        commonParams.setUseFor(1);
        commonParams.setMobile("18521051910");

        String sign = sign2(commonParams);
        System.out.println(sign);
        commonParams.setSign(sign);
    }

    public static String sign2(CommonParams params) throws Exception {

        String[] allFields = ObjectUtils.getFiledName(params);
        //System.out.println(Arrays.toString(allFields));
        Arrays.sort(allFields);

        StringBuilder stringBuilder = new StringBuilder();
        for (String field : allFields) {
            Object value = ObjectUtils.getFieldValueByName(field,params);
            if (value == null) {
                continue;
            }
            stringBuilder.append(field);
            stringBuilder.append("=");
            stringBuilder.append(value);
            stringBuilder.append("&");
        }

        stringBuilder.append("key=");
        stringBuilder.append(key);

        return HMACSHA256Helper.HMACSHA256(stringBuilder.toString(),key);

    }

}
